<script setup lang='ts'>
import { AddParkEnterprise, GetParkEnterpriseAPI, GetParkIndustry, PostUploadAPI, PutParkEnterprise } from '@/apis/park'
import type { Industry, PostParkEnterprise } from '@/types/park'
import { CircleCheck, Upload } from '@element-plus/icons-vue'
import { ElMessage, type FormInstance, type FormRules, type UploadRawFile, type UploadRequestOptions, type UploadUserFile } from 'element-plus'
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const optionValue = ref<Industry[]>([])

const route = useRoute()
// 回显数据
const getData =  async () =>{

  if(route.params.id){
    const res = await GetParkEnterpriseAPI(route.params.id as string)
    console.log('回显数据',res)
    const  { businessLicenseName,industryName, rent, ...filteredData } = res.data
    addForm.value = {
    ...filteredData,
   id: res.data.id?.toString() // 将 number 类型的 id 转换为 string
} 
console.log(businessLicenseName,industryName,rent)
   fileList.value = res.data.businessLicenseUrl
  ? [{ name: res.data.businessLicenseName, url: res.data.businessLicenseUrl }]
  : []
  }  
}
// 如果有id就回显
if(route.params.id){
  getData()
}
// 获取企业行业列表
  const getIndustry = async() =>{
  const res =  await GetParkIndustry()
  console.log('获取企业行业列表',res)
  optionValue.value = res.data
  }   

  getIndustry()

// 用于表单双向数据绑定
const addForm = ref<PostParkEnterprise>({

   id:'',
   /**
     * 上传文件id
     */
    businessLicenseId: undefined,
    /**
     * 上传文件rl
     */
    businessLicenseUrl: '',
    /**
     * 企业联系人
     */
    contact: '',
    /**
     * 企业联系方式
     */
    contactNumber: '',
    /**
     * 行业编号
     */
    industryCode: undefined,
    /**
     * 企业法人
     */
    legalPerson: '',
    /**
     * 企业名称
     */
    name:'',
    /**
     * 注册地址
     */
    registeredAddress:'',
})



// 校验规则
const formRules = ref<FormRules<PostParkEnterprise>>({
  name:[{required:true,message:'请输入企业名称',trigger:'blur'},],
  legalPerson:[{required:true,message:'请输入法人',trigger:'blur'}],
  registeredAddress:[{required:true,message:'请输入注册地址',trigger:'blur'}],
  industryCode:[{required:true,message:'请选择所在行业',trigger:'change'}],
  businessLicenseUrl:[{required:true,message:'请上传营业执照',trigger:'blur'}],
  contact:[{required:true,message:'请输入企业联系人',trigger:'blur'}],
  contactNumber:[{required:true,message:'请输入联系电话',trigger:'blur'},
  {pattern:/^(?:(?:\+|00)86)?1\d{10}$/,message:'请输入正确的手机号',trigger:'blur'}
  ]
})

// 表单统一校验
const formRef = ref<FormInstance>()
const formRef1 = ref<FormInstance>()
// 创建路由器
const router = useRouter()


// 加载状态按钮 禁用提交，避免重复提交
const submitLoading = ref(false)
// 确认提交
const onSubmit =  async()=>{
  try{
      await formRef.value?.validate() 
     await  formRef1.value?.validate()
     submitLoading.value = true
    //  如果有id,调用编辑接口
    if(route.params.id){
     
      await PutParkEnterprise(addForm.value)
    }else{
   //  提交新增请求
    await AddParkEnterprise(addForm.value)
    }
    // 提示
    ElMessage.success(route.params.id ? '编辑成功' :'添加成功')
    router.back()
  }catch(err){
    console.log(err)
    // 提交失败，恢复按钮状态
    submitLoading.value = false
  }
}

// 重置
const Reset = ()=>{
  formRef.value?.resetFields()
  formRef1.value?.resetFields()
  fileList.value = []
  formRef.value?.validateField('businessLicenseUrl')
}

const fileList = ref<UploadUserFile[]>([])
// 自定义上传文件
const onUploadRequest = async(options:UploadRequestOptions) =>{
  
  console.log('options',options)
  // 1.准备formData 对象 
  const fd = new FormData()
  // 2.根据后端要求准备字段
  fd.append('file',options.file)
  fd.append('type','businessLicense')
  // 3.调用接口 上传文件
  const res = await PostUploadAPI(fd)

  console.log('上传文件',res)
  // 业务bug： 上传营业执照完毕之后并不能让校验痕迹消失掉，
  // 原因是因为 el-form 表单校验系统不能得到上传之后的通知
  // 解决办法：单独校验表单，如果校验成功，自动清除错误信息
  addForm.value.businessLicenseUrl = res.data.url
  addForm.value.businessLicenseId = res.data.id
  formRef.value?.validateField('businessLicenseUrl')
  // 将图片路径 return 出去 存储到 fileList 的response 中
  return res.data.url
}
// 文件移除之后的操作
const removeUpload = () =>{
  addForm.value.businessLicenseId = undefined
  addForm.value.businessLicenseUrl = ''
  // 单独校验表单
  formRef.value?.validateField('businessLicenseUrl')
}
// 上传文件之前的操作
const beforeUpload = (file:UploadRawFile) =>{
  const allowImgType = ['image/jpeg','image/png','image/jpg'].includes(file.type)
  const isLt5M = file.size /1024 /1024 < 5
  if(!allowImgType){
    ElMessage.error('上传的文件只能是 PNG/JPG/JPEG格式！')
  }
  if(!isLt5M){
    ElMessage.error('上传的营业执照图片大小不能超过 5MB！')
  }
  return allowImgType && isLt5M
}
</script>
<template>
  <div style="width: 100vw; height: 100vh; background-color: #f4f6f8; display: flex; flex-direction: column;
  justify-content: space-between;
  ">    
  <div>
   <!--顶部 -->    
    <header style="width: 100%; background-color: #fff; height: 64px; display: flex; align-items: center;">
        <el-page-header @back="$router.back()" 
        :content="$route.params.id ? '编辑企业' :' 添加企业'"
        style="margin-left: 20px;"
        ></el-page-header>
    </header>
    <div>
   <!-- 卡片区域 -->
     <main>
        <div style=" background-color: #fff; height: 300px; margin: 20px 130px; padding: 20px">
            <text>企业信息</text>
            <el-form  ref="formRef" :model="addForm" style="margin: 20px 20px 20px 150px;  " label-width="120px" :rules="formRules" >
               <div style="display: flex; " >
                 <el-form-item label="企业名称：" prop="name" style="flex: 1; margin-right: 80px;">
                    <el-input placeholder="请输入企业名称"    v-model="addForm.name"></el-input>
                </el-form-item>
                  <el-form-item label="法人：" prop="legalPerson" style="flex: 1; margin-right: 40px;">
                    <el-input placeholder="请输入法人"  v-model="addForm.legalPerson"></el-input>
                </el-form-item>
               </div>
                 <div style="display: flex; ">   
                 <el-form-item label="注册地址：" prop="registeredAddress" style="flex: 1; margin-right: 80px; ">
                    <el-input placeholder="请输入注册地址"   v-model="addForm.registeredAddress"></el-input>
                </el-form-item>
                  <el-form-item label="所在行业：" prop="industryCode" style="flex: 1;margin-right: 40px; ">
                    <el-select v-model="addForm.industryCode" >
                        <el-option v-for="item in optionValue" 
                        :key="item.industryCode"
                        :value="item.industryCode ?? ''"
                        :label="item.industryName"
                        ></el-option>
                    </el-select>
                </el-form-item>
               </div>
                  <el-form-item label="营业执照：" prop="businessLicenseUrl" style="flex: 1;margin-right: 40px; ">
                     <el-upload
                        class="upload-demo"
                        action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
                        multiple
                        list-type="picture"
                        :limit="1"
                        v-model:file-list="fileList"
                        :http-request="onUploadRequest"
                        accept=".png,.jpg,.jpeg"
                        :before-upload="beforeUpload"
                        :on-remove ="removeUpload"
                      >
                        <el-button  v-if="fileList.length == 0" type="primary" plain :icon="Upload">上传营业执照</el-button>
                        <el-button v-else type="success" :icon="CircleCheck" disabled>已上传</el-button>
                        <template #tip>
                          <div class="el-upload__tip">
                          支持 jpg/png 格式，文件大小不超过 5MB。
                          </div>
                        </template>
                      </el-upload>
                </el-form-item>
            </el-form>
            
        </div>
        <div style="background-color: #fff; height: 100px; margin: 0px 130px; padding: 20px;" >
          <text>联系人信息</text>
          <el-form  ref="formRef1" :model="addForm" style="margin-top: 15px;"  :rules="formRules">
            <div style="display: flex; width: 90%;margin-left: 150px;">
              <el-form-item label="企业联系人：" prop="contact" style="flex: 1; margin-right: 50px;" >
              <el-input placeholder="请输入企业联系人" v-model="addForm.contact" ></el-input>
            </el-form-item> 
              <el-form-item label="联系电话：" prop="contactNumber" style="flex: 1; margin-right: 50px;" >
                <el-input placeholder="请输入联系电话" v-model="addForm.contactNumber"></el-input>
            </el-form-item> 
            </div>
          </el-form>
        </div>
     </main>
    </div>
  </div>
    <!-- 底部 -->
     <footer>
        <div style="width: 100vw; background-color: #fff; height: 64px; display: flex;justify-content: center;align-items: center;" >
            <el-button @click="Reset()">重置</el-button>
            <el-button  :loading="submitLoading" type="primary" @click="onSubmit()">{{ submitLoading ? '提交中' :'确定' }}</el-button>
        </div>
     </footer>
  </div>
</template>


<style lang='scss' scoped>

</style>